package com.jxc.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.AgencyGrantRecord;
import com.jxc.model.po.Repertory;
import com.jxc.model.po.Resource;
import com.jxc.model.po.Role;
import com.jxc.model.po.RoleResource;
import com.jxc.model.po.User;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VUser;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.UserServiceI;
import com.jxc.util.MD5;

@Service("userService")
public class UserServiceImpl implements UserServiceI {

	@Autowired
	private BaseDaoI<User> userDao;
	@Autowired
	private BaseDaoI<AgencyGrantRecord> agencyDao;
	@Autowired
	private BaseDaoI<Repertory> repertoryDao;

	@Override
	public VUser get(Long id) {
		return this.changeModel(userDao.get(User.class, id));
	}

	@Override
	public List<VUser> combobox(VUser vuser) {
		List<VUser> vusers = new ArrayList<VUser>();
		vusers.addAll(this.changeModel(this.find(vuser, null)));
		return vusers;
	}

	private List<VUser> changeModel(List<User> users) {
		List<VUser> vusers = new ArrayList<VUser>();
		if (users != null && users.size() > 0) {
			for (User user : users) {
				VUser vuser = new VUser();
				BeanUtils.copyProperties(user, vuser);

				Role role = user.getRole();
				vuser.setRoid(role.getId());
				vuser.setRoname(role.getName());

				if (user.getRepertory() != null) {
					Repertory repertory = user.getRepertory();
					vuser.setReid(repertory.getId());
					vuser.setRename(repertory.getName());
				}

				vusers.add(vuser);
			}
		}
		return vusers;
	}

	private VUser changeModel(User user) {
		if (user == null)
			return null;

		VUser vuser = new VUser();
		BeanUtils.copyProperties(user, vuser, new String[] { "password" });

		Role role = user.getRole();
		vuser.setRoid(role.getId());
		vuser.setRoname(role.getName());

		if (user.getRepertory() != null) {
			Repertory repertory = user.getRepertory();
			vuser.setReid(repertory.getId());
			vuser.setRename(repertory.getName());
		}

		return vuser;
	}

	private List<User> find(VUser vUser, VUser vuser) {
		String hql = "from User t where t.isDeleted=false and t.username!='admin' ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vUser, vuser, hql, values);

		if (vUser.getSort() != null && vUser.getOrder() != null) {
			hql += " order by " + vUser.getSort() + " " + vUser.getOrder();
		}
		return userDao.find(hql, values, vUser.getPage(), vUser.getRows());
	}

	private Long total(VUser vUser, VUser vuser) {
		String hql = "select count(*) from User t where t.isDeleted=false and t.username!='admin' ";
		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vUser, vuser, hql, values);
		return userDao.count(hql, values);
	}

	private String addWhere(VUser vUser, VUser vuser, String hql,
			List<Object> values) {
		if (vUser.getUsername() != null
				&& !vUser.getUsername().trim().equals("")) {
			hql += " and t.username like ? ";
			values.add("%%" + vUser.getUsername().trim() + "%%");
		}

		if (vUser.getUserType() != null) {
			hql += " and t.userType = ? ";
			values.add(vUser.getUserType());
		}

		if (vUser.getRoid() != null) {
			hql += " and t.role.id = ? ";
			values.add(vUser.getRoid());
		}

		if (vUser.getReid() != null) {
			hql += " and t.repertory.id = ? ";
			values.add(vUser.getReid());
		}
		if (vuser != null) {
				hql += " and t.user.id = ? ";
				values.add(vuser.getId());
		}
		return hql;
	}

	@Override
	public VUser login(VUser user) {
		String hql = "from User u where u.isDeleted=false and u.username = ? and u.password = ? and u.validDate <= ? and u.expiryDate > ? and u.status = ?";
		User dUser = userDao.get(hql, new Object[] { user.getUsername(),
				MD5.md5(user.getPassword()), new Date(), new Date(), 1 });
		VUser u = changeModel(dUser);
		if (u != null) {
			u.setPassword(user.getPassword());
			Map<Long, String> authIdsMap = new HashMap<Long, String>();
			String authIds = "";
			String authNames = "";
			Map<Long, String> authUrlsMap = new HashMap<Long, String>();
			String authUrls = "";
			List<RoleResource> roleResources = dUser.getRole()
					.getRoleResources();
			if (roleResources != null && roleResources.size() > 0) {
				for (RoleResource roleResource : roleResources) {
					Resource resource = roleResource.getResource();
					authIdsMap.put(resource.getId(), resource.getName());
					authUrlsMap.put(resource.getId(), resource.getUrl());
				}
			}
			boolean b2 = false;
			for (Long id : authIdsMap.keySet()) {
				if (b2) {
					authIds += ",";
					authNames += ",";
				}
				authIds += id;
				authNames += authIdsMap.get(id);
				b2 = true;
			}
			u.setAuthIds(authIds);
			u.setAuthNames(authNames);
			boolean b3 = false;
			for (Long id : authUrlsMap.keySet()) {
				if (b3) {
					authUrls += ",";
				}
				authUrls += authUrlsMap.get(id);
				b3 = true;
			}
			u.setAuthUrls(authUrls);
		}
		return u;
	}

	@Override
	public DataGrid datagrid(VUser vuser) {
		DataGrid j = new DataGrid();
		j.setRows(this.changeModel(this.find(vuser, null)));
		j.setTotal(this.total(vuser, null));
		return j;
	}

	@Override
	public void delete(String ids) {
		if (ids != null) {
			for (String id : ids.split(",")) {
				if (!id.trim().equals("0")) {
					User u = userDao.get(User.class, Long.valueOf(id.trim()));
					if (u != null) {
						u.setIsDeleted(true);
						userDao.update(u);
					}
				}
			}
		}

	}

	@Override
	public void editUserInfo(VUser vuser) {
		if (vuser.getPassword() != null
				&& !vuser.getPassword().trim().equals("")) {
			User t = userDao.get(User.class, vuser.getId());
			t.setPassword(MD5.md5(vuser.getPassword()));
		}

	}

	@Override
	public void save(VUser vuser) {
		User u = new User();
		BeanUtils.copyProperties(vuser, u, new String[] { "password" });
		if (vuser.getCreateTime() == null) {
			u.setCreateTime(new Date());
		}
		if (vuser.getRoid() != null) {
			Role role = new Role();
			role.setId(vuser.getRoid());
			u.setRole(role);
		}
		if (vuser.getReid() != null) {
			Repertory repertory = repertoryDao.get(Repertory.class, vuser.getReid());
			u.setRepertory(repertory);
			User user = repertory.getUser();
			u.setUser(user);
		}
		u.setIsDeleted(false);
		u.setPassword(MD5.md5(vuser.getPassword()));
		userDao.save(u);
	}

	@Override
	public void update(VUser vuser) {
		User u = userDao.get(User.class, vuser.getId());
		BeanUtils.copyProperties(vuser, u, new String[] { "id", "password" });
		if (vuser.getCreateTime() == null) {
			u.setCreateTime(new Date());
		}
		if (vuser.getPassword() != null
				&& !vuser.getPassword().trim().equals("")) {
			u.setPassword(MD5.md5(vuser.getPassword()));
		}
		if (vuser.getRoid() != null) {
			Role role = new Role();
			role.setId(vuser.getRoid());
			u.setRole(role);
		}
		if (vuser.getReid() != null) {
			Repertory repertory = repertoryDao.get(Repertory.class, vuser.getReid());
			u.setRepertory(repertory);
			User user = repertory.getUser();
			u.setUser(user);
		}
		u.setIsDeleted(false);
		userDao.update(u);

	}

	@Override
	public List<VUser> agency(VUser vUser) {
		String hql = "select t.user from Brand t where t.isDelete=false and t.repertory.user.id=? group by t.user";
		List<Object> values = new ArrayList<Object>();
		values.add(vUser.getId());
		List<User> users = userDao.find(hql, values);
		List<User> exit = new ArrayList<User>();
		if (users != null && users.size() > 0) {
			for (User user : users) {
				String hql2 = "from AgencyGrantRecord t where t.agency.id=? and t.dealer.id=?";
				List<Object> values2 = new ArrayList<Object>();
				values2.add(user.getId());
				values2.add(vUser.getId());
				List<AgencyGrantRecord> agencys = agencyDao.find(hql2, values2,
						1, 1);
				if (agencys != null && agencys.size() > 0) {
					exit.add(user);
				}
			}
			users.removeAll(exit);
		}
		return changeModel(users);
	}

	@Override
	public void changePassword(VUser vUser) {
		User u = userDao.get(User.class, vUser.getId());
		if (vUser.getPassword() != null
				&& !vUser.getPassword().trim().equals("")) {
			u.setPassword(MD5.md5(vUser.getPassword()));
			userDao.update(u);
		}

	}

	@Override
	public List<VUser> combobox(VUser vUser, VUser vuser) {
		List<VUser> vusers = new ArrayList<VUser>();
		vusers.addAll(this.changeModel(this.find(vUser, vuser)));
		return vusers;
	}

	@Override
	public DataGrid datagrid(VUser vUser, VUser vuser) {
		DataGrid j = new DataGrid();
		j.setRows(this.changeModel(this.find(vUser, vuser)));
		j.setTotal(this.total(vuser, vuser));
		return j;
	}
}
